from rdb import RDB, ModelDB
from pathlib import Path
from rdb import constdb
import re


class RController:
    def __init__(self, db: RDB):
        self._db = db

    def init_param(self):
        """ First init model directory to model name dict,
            then init other dicts """
        release_path = Path(self._db.get_release_dir())
        for x in release_path.iterdir():
            if self._is_fw_src(x):
                model = self._parse_model_name(x)
                if model:
                    model_db = ModelDB(x, model, self._db)
                    model_db.init()
                    self._db.append_model(model_db)
                    self._db.set_dir_model(x.__str__(), model)
                    self._db.set_model_dir(model, x.__str__())

    def _parse_model_name(self, fw_dir: Path):
        env_file = fw_dir.joinpath(constdb.env_file())
        if env_file.exists() is False:
            return None

        model_name = None
        with open(env_file, mode='r') as f:
            for line in f:
                m = re.search('(?<=export MODEL_NAME=)[a-zA-Z0-9-]+', line)
                if m is not None:
                    model_name = m.group(0)
                    break

        return model_name

    def _is_fw_src(self, p: Path):
        cust_dir = p.joinpath(constdb.cust_inc_dir())
        return cust_dir.exists()
